package com.gitee.wsl.statemachine.state

import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.produceState
import com.gitee.wsl.statemachine.StateMachine
import kotlinx.coroutines.ExperimentalCoroutinesApi


/**
 * Get a Compose [State] object from a [FlowReduxStateMachine].
 *
 * The returned [State.value] can be `null`.
 * `null` means that the [FlowReduxStateMachine] has not emitted a state yet.
 * That is the case when the coroutine has launched to collect [FlowReduxStateMachine.state]
 * but since it runs async in a coroutine (a new coroutines is launched under
 * the hood of [rememberState]) the [FlowReduxStateMachine] has not emitted state yet
 * while Jetpack Compose continue its work on the main thread.
 * Therefore, `null` is used as some sort of initial value and the first value of
 * [FlowReduxStateMachine] is emitted just a bit later (non null value then).
 */
@ExperimentalCoroutinesApi
@Composable
fun <A,  S> StateMachine<A, S>.rememberState(): State<S?> {
    return produceState<S?>(initialValue = null, this) {
        state.collect { value = it }
    }
}